<?php

class Red
{
	private $total_amount;

	private $number;

	private $min_amount;

	public function __construct($total_amount, $number = 0, $min_amount = 0.01)
	{
		$this->parse($total_amount, $number, $min_amount);
	}

	/**
	 * [parse description]
	 * @param  [type] $total_amount [description]
	 * @param  [type] $number       [description]
	 * @param  [type] $min_amount   [description]
	 * @return [type]               [description]
	 */
	private function parse($total_amount, $number, $min_amount)
	{
		if($total_amount <= 0){
			throw new \Exception('总额不可为0');
		}
		if($number <= 0){
			throw new \Exception('总数不可为0');
		}
		if($min_amount < 0.01){
			throw new \Exception('最小金额不能低于0.01');
		}
		if($total_amount < $min_amount * $number){
			throw new \Exception('金额不足');
		}
		$this->total_amount = $total_amount;
		$this->number = $number;
		$this->min_amount = $min_amount;
	}

	public function randomAmountLevel()
	{
		$free_amount = $this->total_amount - ($this->number * $this->min_amount);
		//var_dump($free_amount);
		$package = [];
		if($free_amount <= 0){
			for ($i=0; $i < $this->number; $i++) { 
				$package[] = sprintf("%.2f",$this->min_amount);
			}
			return $package;
		}
		$average_amount = $free_amount / $this->number;

		for ($i = 1; $i <= $this->number; $i++) {
			if($i == $this->number){
				$package[] = sprintf("%.2f",$free_amount + $this->min_amount);
				break;
			}
			
			$safe_amount = ($free_amount - ($this->number - $i) / 100) / ($this->number - $i);
			$amount = mt_rand((int)($average_amount *  mt_rand(10,99900) / 100000), (int)($safe_amount * 100)) / 100;
			$free_amount -= $amount;
			$package[] = sprintf("%.2f",($amount + $this->min_amount));
		}
		shuffle($package);
		return $package;

	}

}

$obj = new Red(10,4,1);
$data = $obj->randomAmountLevel();
print_r($data);

print_r(array_sum($data));